package com.mcp.converter.domain.rule.compatibility.function;

import com.mcp.converter.domain.checker.IncompatibilityDetail;
import com.mcp.converter.shared.response.sql.SQLElement;
import com.mcp.converter.domain.rule.compatibility.AbstractFunctionRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 高级函数兼容性规则
 * 包含确认在OceanBase中不支持的Oracle高级函数
 * @author zengxiong
 */
public class AdvancedFunctionRule extends AbstractFunctionRule {
    private static final String RULE_ID = "FN015";
    private static final String RULE_NAME = "高级函数不兼容";
    private static final String RULE_DESCRIPTION = "OceanBase不支持的Oracle高级函数";

    private static final Set<String> ADVANCED_FUNCTIONS = new HashSet<>(Arrays.asList(
        // 数据挖掘函数（OceanBase不支持Oracle Data Mining）
        "CLUSTER_ID", "CLUSTER_PROBABILITY", "CLUSTER_SET", "CLUSTER_DETAILS",
        "FEATURE_ID", "FEATURE_SET", "FEATURE_VALUE", "FEATURE_DETAILS",
        "PREDICTION", "PREDICTION_COST", "PREDICTION_DETAILS", "PREDICTION_PROBABILITY", "PREDICTION_SET",
        "ORA_DM_PARTITION_NAME",
        
        // 空间数据函数（OceanBase不支持Oracle Spatial）
        "SDO_GEOMETRY", "SDO_POINT_TYPE", "SDO_ELEM_INFO_ARRAY", "SDO_ORDINATE_ARRAY",
        "SDO_AREA", "SDO_BUFFER", "SDO_CENTROID", "SDO_DISTANCE", "SDO_LENGTH",
        "SDO_INTERSECTION", "SDO_UNION", "SDO_WITHIN_DISTANCE", "SDO_CONTAINS",
        
        // 全文检索函数（OceanBase不支持Oracle Text）
        "CONTAINS", "CATSEARCH", "MATCHES", "SCORE",
        
        // 高级统计函数（OceanBase不支持）
        "STATS_BINOMIAL_TEST", "STATS_CROSSTAB", "STATS_F_TEST", "STATS_KS_TEST",
        "STATS_MODE", "STATS_MW_TEST", "STATS_ONE_WAY_ANOVA", "STATS_T_TEST_ONE",
        "STATS_T_TEST_PAIRED", "STATS_T_TEST_INDEP", "STATS_WSR_TEST",
        
        // 模型函数（OceanBase不支持Oracle Model子句）
        "CV", "ITERATION_NUMBER", "PRESENTNNV", "PRESENTV", "PREVIOUS",
        
        // 集合操作函数（OceanBase对嵌套表支持有限）
        "POWERMULTISET", "POWERMULTISET_BY_CARDINALITY", "SET",
        
        // 高级聚合和分析函数（仅保留确实不支持的）
        "APPROX_PERCENTILE_CONT", "APPROX_PERCENTILE_DISC", "APPROX_RANK", "APPROX_SUM",
        "CARDINALITY", "COLLECT", "CORR_K", "CORR_S", 
        "FIRST", "GROUP_ID", "GROUPING_ID", "LAST"
    ));

    private static final Logger log = LoggerFactory.getLogger(AdvancedFunctionRule.class);

    public AdvancedFunctionRule() {
        super(RULE_ID, RULE_NAME, RULE_DESCRIPTION);
        setIncompatibilityDetail(
            "OceanBase不支持以下确认的Oracle高级函数：\n" +
            "1. 数据挖掘函数：CLUSTER_*、FEATURE_*、PREDICTION_*等（需要Oracle Data Mining选项）\n" +
            "2. 空间数据函数：SDO_*系列函数（需要Oracle Spatial选项）\n" +
            "3. 全文检索函数：CONTAINS、CATSEARCH、MATCHES、SCORE（需要Oracle Text选项）\n" +
            "4. 高级统计函数：STATS_*系列函数\n" +
            "5. 模型函数：CV、ITERATION_NUMBER、PRESENTNNV等（需要Model子句支持）\n" +
            "6. 部分集合操作函数：POWERMULTISET、SET等",
            "可能导致：\n" +
            "1. 数据挖掘相关功能失效\n" +
            "2. 空间数据查询和计算失败\n" +
            "3. 全文检索功能不可用\n" +
            "4. 高级统计分析无法进行\n" +
            "5. 模型预测查询失败",
            "建议：\n" +
            "1. 数据挖掘：迁移到专门的数据挖掘平台或工具\n" +
            "2. 空间数据：使用PostGIS等专门的空间数据库扩展\n" +
            "3. 全文检索：使用Elasticsearch等专门的搜索引擎\n" +
            "4. 统计分析：使用应用层统计计算或简化算法\n" +
            "5. 模型预测：将预测逻辑迁移到应用层或机器学习平台",
            IncompatibilityDetail.Severity.HIGH
        );
    }

    @Override
    public boolean matches(Object target) {
        log.debug("[AdvancedFunctionRule] 开始匹配检查");
        
        if (!(target instanceof SQLElement)) {
            log.debug("[AdvancedFunctionRule] 目标对象不是SQLElement类型");
            return false;
        }

        SQLElement element = (SQLElement) target;
        log.debug("[AdvancedFunctionRule] 检查SQL元素: type={}, name={}, value={}", 
            element.getType(), element.getName(), element.getValue());

        if (!isFunctionElement(element)) {
            log.debug("[AdvancedFunctionRule] 元素不是函数类型");
            return false;
        }

        String functionName = element.getName().toUpperCase().trim();
        log.debug("[AdvancedFunctionRule] 正在检查函数名: {}", functionName);
        
        boolean match = ADVANCED_FUNCTIONS.contains(functionName);
        log.debug("[AdvancedFunctionRule] 函数匹配结果: name={}, match={}", functionName, match);
        
        if (match) {
            log.warn("[AdvancedFunctionRule] 发现不兼容的高级函数: {}", functionName);
        }

        return match;
    }
    
    @Override
    public Set<String> getIncompatibleFunctions() {
        return new HashSet<>(ADVANCED_FUNCTIONS);
    }
}